package com.yomahub.tlog.feign.filter;

import com.yomahub.tlog.context.SpanIdGenerator;
import com.yomahub.tlog.context.TLogContext;
import com.yomahub.tlog.utils.LocalhostUtil;
import feign.RequestInterceptor;
import feign.RequestTemplate;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * feign的拦截器
 *
 * @author Bryan.Zhang
 * @since 1.0.0
 */
public abstract class AbstractTLogFeignFilter implements RequestInterceptor {

    private static final Logger log = LoggerFactory.getLogger(AbstractTLogFeignFilter.class);

    /**
     * @param traceId
     * @param hostName
     * @param hostIp
     * @param nextSpanId
     * @param requestTemplate
     */
    public abstract void doApply(String traceId, String hostName, String hostIp, String nextSpanId, RequestTemplate requestTemplate);

    @Override
    public void apply(RequestTemplate requestTemplate) {
        String traceId = TLogContext.getTraceId();
        if (StringUtils.isNotBlank(traceId)) {
            String hostName = LocalhostUtil.getHostName();
            String hostIp = LocalhostUtil.getHostIp();
            String nextSpanId = SpanIdGenerator.generateNextSpanId();
            doApply(traceId, hostName, hostIp, nextSpanId, requestTemplate);
        } else {
            log.debug("[TLOG]本地threadLocal变量没有正确传递traceId,本次调用不传递traceId");
        }
    }
}